import {getInfo, login, logout} from '@/api/user'
import {getToken, removeToken, setToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    bind_city: '',
    bind_cid: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_CITY: (state, bind_city) => {
    state.bind_city = bind_city
  },
  SET_CID: (state, user_cid) => {
    state.bind_cid = user_cid
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    const {phone, code,loginType,username,password} = userInfo
    return new Promise((resolve, reject) => {
      login({phone: phone.trim(), code: code,loginType:loginType,username:username,password:password}).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {user_name, user_verify, roles, bind_city, user_cid} = data
        commit('SET_NAME', user_name ? user_name : user_verify)
        commit('SET_CITY', bind_city ? bind_city : '')
        commit('SET_CID', user_cid ? user_cid : '0')
        commit('SET_ROLES', roles)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  tokenLogin({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', userInfo.token)
      setToken(userInfo.token)
      resolve()
    })
  },
  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

